import React, { JSX, useRef, useState } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { OrbitControls, useHelper } from "@react-three/drei";
import * as THREE from "three";

// 3D 立方体组件
function Box(props: JSX.IntrinsicElements["mesh"]) {
  // 获取对 mesh 的引用以便直接访问
  const meshRef = useRef<THREE.Mesh>(null);
  // 设置悬停和点击状态
  const [hovered, setHover] = useState(false);
  const [active, setActive] = useState(false);

  // 添加方向光辅助线（开发时可见）
  const directionalLightRef = useRef<THREE.DirectionalLight>(null);
  // useHelper(directionalLightRef, THREE.DirectionalLightHelper, 1, "white");

  // 每一帧旋转立方体
  useFrame((state, delta) => {
    if (meshRef.current) {
      meshRef.current.rotation.x += delta * 0.5;
      meshRef.current.rotation.y += delta * 0.2;
    }
  });

  return (
    <>
      {/* 方向光 */}
      <directionalLight
        ref={directionalLightRef}
        position={[5, 5, 5]}
        intensity={1}
        castShadow
      />
      {/* 环境光 */}
      <ambientLight intensity={0.5} />

      {/* 立方体 mesh */}
      <mesh
        {...props}
        ref={meshRef}
        scale={2.5}
        // onClick={() => setActive(!active)}
        onPointerOver={() => setHover(true)}
        onPointerOut={() => setHover(false)}
        castShadow
      >
        <boxGeometry args={[1, 1, 1]} />
        <meshStandardMaterial color={hovered ? "hotpink" : "orange"} />
      </mesh>
    </>
  );
}

// 场景组件
function Scene() {
  return (
    <Canvas
      shadows
      camera={{ position: [3, 3, 3], fov: 75 }}
      style={{ height: "30vh", width: "100%" }}
    >
      {/* 添加轨道控制器，可以用鼠标旋转/缩放/平移场景 */}
      <OrbitControls />

      {/* 添加一个平面用于接收阴影 */}
      {/* <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, -1, 0]} receiveShadow>
        <planeGeometry args={[10, 10]} />
        <meshStandardMaterial color="#f0f0f0" />
      </mesh> */}

      {/* 我们的立方体 */}
      <Box position={[0, 0, 0]} />
    </Canvas>
  );
}

// 主组件
export default function Basic3DModel() {
  return (
    <div style={{ width: "100%", height: "30vh" }}>
      <Scene />
    </div>
  );
}
